package 
{
import com.adobe.serialization.json.JSONDecoder;
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.system.*;
import flash.text.*;
import flash.ui.*;
import flash.utils.Timer;
import flash.utils.*;
import flash.xml.*;
import flash.text.engine.JustificationStyle;
import flash.display.DisplayObject;

	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.text.TextField;
	import caurina.transitions.Tweener;
	import flash.utils.Timer;


	public class TwitterDing extends Sprite
	{
		private var _users:Object;
		private var i:int = 0;
		private var data:Object;
		protected var refreshTimer:Timer;
		private var usertext:TextField;
		private var yPos:Number = 0;
		private var tweetArray:Array = new Array();
		private var tweet:Object;
		
		private var MC:MovieClip;
		public var container:MovieClip;
		private var array:Array;
		private var nummer1:Number;
		private var nummer2:Number;
		private var nummer3:Number;
		private var sprite:Sprite;
		private var textformat:TextFormat;
		private var imageloader:Loader;
		private var userimage:URLRequest;
		private var removetweet:DisplayObject;
		private var interfacebutton:SimpleButton;
		private var countarray:Array;
		private var tweets:Array;
		private var oldtweets:Array;
		private var newesttweetid:Number;
		private var textformattime:TextFormat;
		private var logogrootloader:Loader;
		private var logokleinloader:Loader;
		private var logotwitterloader:Loader;
		private var introtext:TextField;
		private var textformatintro:TextFormat;
		
		//Main functie
		public function TwitterDing()
		{
			this.tweetArray = [];
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
			
			trace("height" + stage.stageHeight);
			trace("width" + stage.stageWidth);
			newesttweetid = 0;
			tweets = new Array();

		}
		// initialiseer, eventlistener weg, URL laden van twitter.com
		public function init(e:Event = null):void
		{
			//create timer with 1000 ms delay -> is 1 seccond. 
			this.refreshTimer = new Timer(5000)
			//add listener for each tick
			this.refreshTimer.addEventListener(TimerEvent.TIMER , onTimerTick);
			//start timer otherwise it wont tick
			this.refreshTimer.start();
			
			logogrootloader = new Loader();
			logogrootloader.load(new URLRequest("logogroot.png"));
			addChild(logogrootloader);

			
			sprite = new Sprite();
			
			sprite.graphics.beginFill(0x999999, 0.6);
			sprite.graphics.drawRoundRect(10, 10, 1260, 740, 15, 15);
			sprite.graphics.lineStyle(10, 0xc0c0c0);
			sprite.graphics.endFill();
			addChild(sprite);
			
			logokleinloader = new Loader();
			logokleinloader.load(new URLRequest("logoklein.png"));
			logokleinloader.x = 20;
			logokleinloader.y = 30;
			addChild(logokleinloader);
			
			textformatintro = new TextFormat();
			textformatintro.size = 70;
			textformatintro.bold = true;
			textformatintro.color = "0xf0f0f0"
			
			introtext = new TextField();
			introtext.defaultTextFormat = textformatintro;
			introtext.text = "Tweet #CMI";
			introtext.width = 500;
			introtext.height = 100;
			introtext.x = 310;
			introtext.y = 40;
			addChild(introtext);
			
			logotwitterloader = new Loader();
			logotwitterloader.load(new URLRequest("logotwitter.png"));
			addChild(logotwitterloader);
			
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
			
		}
		//TODO make userinterface to change tags
		protected function onTimerTick(e:TimerEvent):void {
			//tick tick
			trace("tick");
			
			var tag:String = "%23CMI"
			var url:String = "http://search.twitter.com/search.json?q="

			var urlReq:URLRequest 
				= new URLRequest(url+tag);
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onDataLoaded);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, 
				 onSecurityError);
			loader.load(urlReq);
			
			
			
		}

		// Maak er een Json van en stuur m naar een tekstveldfunctie
		//TODO highlight #tags and links, show username/timetweeted, get avatars to work...
		private function onDataLoaded(e:Event):void {
			
			data = new JSONDecoder(e.target.data, false).getValue();
			trace(e.target.data);
			
						
			for (var index:uint = 0; index < data.results.length; index++) 
			{
				_users = data.results[index];
				
				if(_users.id != newesttweetid){
				
				tweets.push(_users);
				
				}
				else 
				{
					break
				}
			}
			
			newesttweetid = data.results[0].id;
			
			if (tweets.length != 0)
			{
			
				_users = tweets.pop();
				

				//trace(_users.created_at)
				
				
				
				// Create container
				container = new MovieClip()
				nummer1 = ((sprite.width/2) * Math.random())+5;
				nummer2 = ((sprite.height/2) * Math.random())+100;
				nummer3 = (Math.random() - 0.5) * 25;
				container.x = nummer1;
				container.y = nummer2;
				this.addChild(container);
				
				this.tweetArray.push(container);
				
				//container.graphics.drawRect(0, 0, 840, 240);
				
				var MCback:MovieClip = new MovieClip();
				MCback.graphics.beginFill(0xc0c0c0);
				MCback.graphics.drawRoundRect(container.x-244, container.y-64, 1268, 368, 15, 15);
				MCback.graphics.lineStyle(2, 0x000000, 1, true);
				MCback.graphics.endFill();
				container.addChild(MCback);
				
				MC = new MovieClip()
				MC.graphics.beginFill(0x232323);
				MC.graphics.drawRoundRect(container.x-240, container.y-60, 1260, 360, 15, 15);
				MC.graphics.lineStyle(2, 0x000000, 1, true);
				MC.graphics.endFill();
				container.addChild(MC);
				
				imageloader = new Loader();
				userimage = new URLRequest(_users.profile_image_url);
				imageloader.load(userimage);
				MC.addChild(imageloader);
				imageloader.x = (container.x-240) + 45;
				imageloader.y = (container.y-60) + 80;
				imageloader.scaleX = 4;
				imageloader.scaleY = 4;
				
				textformat = new TextFormat();
				//textformat.font = "Verdana";
				textformat.size = 50;
				textformat.color = "0xffffff"
				
				var textField:TextField = new TextField();
				textField.defaultTextFormat = textformat;
				textField.height = 330;
				textField.width = 930;
				textField.x = (container.x-40) + 70;
				textField.y = (container.y-60) + 20;
				//textField.border = 1;
				textField.wordWrap = true;
				_users.text = "<b>"+_users.from_user+"</b> " + _users.text;
				textField.htmlText = _users.text;
				MC.addChild(textField);
				
				textformattime = new TextFormat();
				//textformat.font = "Verdana";
				textformattime.size = 24;
				textformattime.color = "0xf0f0f0"
				
				var timetextfield:TextField = new TextField();
				timetextfield.defaultTextFormat = textformattime;
				timetextfield.height = 50;
				timetextfield.width = 620;
				timetextfield.x = (container.x-40) + 70;
				timetextfield.y = (container.y) + 240;
				timetextfield.wordWrap = true;
				timetextfield.htmlText = _users.created_at;
				MC.addChild(timetextfield);
				
				
				Tweener.addTween(container, { height:textField.height * 0.6, width:textField.width * 0.6, rotationZ:nummer3, time:4, transition:"easein" } );
			}
			
			/*
			for each (var displayObject:DisplayObject in this.tweetArray)
			{
				this.removeChild(displayObject);
			}
			*/
			
			this.tweetArray = [];
			
			 //for (var; voorwaarde; verhoging)
			//for(var index:uint = 0; index < data.results.length; index++)
			//{
				//
				//
				//_users = data.results[index];
				//trace(_users.created_at)
				//
				//tweetArray.push(imageloader = new Loader);
				//tweetArray.push(userimage = new URLRequest(_users.profile_image_url));
				//imageloader.load(userimage);
				//addChild(imageloader);
				//imageloader.x = 20;
				//imageloader.y = 20;
				//imageloader.width = 100;
				//imageloader.height = 100;
				//trace(_users.profile_image_url);
				//
				 //Create container
				//container = new MovieClip()
				//nummer1 = ((sprite.width/2) * Math.random())+5;
				//nummer2 = ((sprite.height/2) * Math.random())+100;
				//nummer3 = (Math.random() - 0.5) * 25;
				//container.x = nummer1 + 300;
				//container.y = nummer2 + 100;
				//this.addChild(container);
				//this.tweetArray.push(container);
				//
				//container.graphics.drawRect(0, 0, 840, 240);
				//
				//MC = new MovieClip()
				//MC.graphics.beginFill(0xFF0000);
				//MC.graphics.drawRoundRect(container.x-240, container.y-60, 840, 240, 10, 10);
				//MC.graphics.lineStyle(2, 0x000000, 1, true);
				//MC.graphics.endFill();
				//container.addChild(MC);
				//
				//textformat = new TextFormat();
				//textformat.font = "Verdana";
				//textformat.size = 34;
				//textformat.color = "0xffffff"
				//
				//var textField:TextField = new TextField();
				//textField.defaultTextFormat = textformat;
				//textField.height = 220;
				//textField.width = 620;
				//textField.x = (container.x-40) + 10;
				//textField.y = (container.y-60) + 10;
				//textField.border = 1;
				//textField.wordWrap = true;
				//textField.text = _users.text;
				//MC.addChild(textField);
				//
				//Tweener.addTween(container, { height:textField.height * 0.5, width:textField.width * 0.5, rotationZ:nummer3, time:4, transition:"easein" } );
				
			
		}
		
		private function removeTweet(e:Event):void
		{
			
			removeChild(removetweet);
			trace(tweetArray.length);
				
			
		}

		
		// Bestand kan niet geladen worden
		private function onIOError(e:Event):void {
			// handle error
			trace("onoz")
		}

		// geen toestemming om URL te downloaden
		private function onSecurityError(e:Event):void {
			// handle error
			trace("zomg noes")
		}
	}
}